from backend import models
from django.contrib.auth import authenticate
from jump_king.lib import demo
class Ssh_handler(object):
    def auth(self):
        count=0
        while count <=3:
            username=input('用户名：>>')
            password=input('密码：>>')
            user=authenticate(username=username,password=password)
            if user:
                self.user=user
                count=0
                return True
            else:
                count +=1
                continue
        else:
            return False

    def host_list(self):
        if self.auth():
            while True:
                groups=self.user.host_groups.all()
                print('你所能操作的服务器组：')
                for index,group in enumerate(groups):
                    print('[%s]  ----  %s'%(index,group))
                print('输入Z显示未分组主机：>>')
                choice=input('请选择要操作的组：>>').strip()
                if choice == 'Z' or choice == 'z':
                    group=self.user
                else:
                    choice=int(choice)
                    group=groups[choice]
                while True:
                    try:
                        for index,host in enumerate(group.host_to_remote_users.all()):
                            print('[%s]  ----  %s'%(index,host))
                            print('输入b返回上级菜单')
                        choice=input('请选择要操作的主机：>>').strip()
                        if choice == 'b':
                                break
                        choice=int(choice)
                        host=group.host_to_remote_users.all()[choice]
                        self.user.auditlog=models.Audit_Log
                        demo.start_connect(user_obj=self.user,host=host)

                    except Exception:
                        print('输入错误')




        else:
            print('认证失败')
